package cn.player.media.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

import cn.player.R;
import cntv.player.core.util.LogUtil;
import cntv.player.core.util.StringUtil;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.widget.BaseMediaController;

public class StarMediaController extends BaseMediaController {
    private static final String TAG = "zl";
    private static final int mDefaultTimeout = 5000;
    private static final int FADE_OUT_CONTROLLER = 1;
    private static final int SHOW_PLAY_PROGRESS = 2;
    private static final int SHOW_BUFFER_PROGRESS = 3;
    private static final int REMOVE_CONTROLLER = 6;

    private Context mContext;

    private View mRoot;
    private ViewGroup mAnchor;
    private SeekBar mScheduleProgress;// 进度条

    public boolean mShowing;

    private long mDuration;
    protected long newPosition;
    protected long nowPosition;
    protected int newPercent;
    protected String newTime;
    private int mProgress;

    private OnShownListener mShownListener;
    private OnHiddenListener mHiddenListener;

    private OnSeekBarChangeListener mSeekListener;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FADE_OUT_CONTROLLER:
                    hide();
                    break;
                case SHOW_PLAY_PROGRESS:
                    updatePlayProgress();
                    break;
                case REMOVE_CONTROLLER:
                    if (mAnchor != null) {
                        mAnchor.removeView(mRoot);
                        mShowing = false;
                        LogUtil.i("zl", "MediaController hide mAnchor.removeView(mRoot)...");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public StarMediaController(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public StarMediaController(Context context) {
        super(context);
        mContext = context;
    }

    @Override
    public void onFinishInflate() {
        super.onFinishInflate();
        if (mRoot != null) {
            initControllerView(mRoot);
        }
    }

    @Override
    protected void setPlayerListeners() {
        // TODO Auto-generated method stub
        super.setPlayerListeners();

        if (mVideoView != null) {
            mVideoView.setOnSlideListener(new MySlideListener());
        }
    }

    /**
     * 设置MediaController 所依附的的父视图
     */
    @Override
    protected void setAnchorView(ViewGroup view) {
        // TODO Auto-generated method stub
        mAnchor = view;
        mRoot = getControllerView();
        setViewListeners();
        initControllerView(mRoot);
        show();
    }

    /**
     * 获取依附的父视图
     *
     * @return
     */
    public View getAnchorView() {
        return mAnchor;
    }

    /**
     * 默认控制器视图
     *
     * @return
     */
    protected View makeControllerView() {
        return LayoutInflater.from(mContext).inflate(R.layout.player_control_vod_star_fullscreen, this);
    }

    private void initControllerView(View rootView) {

        mScheduleProgress = (SeekBar) rootView.findViewById(R.id.sb_player_seekbar);
        if (mScheduleProgress != null) {
            mScheduleProgress.setOnSeekBarChangeListener(mSeekListener);
            mScheduleProgress.setThumbOffset(1);
            mScheduleProgress.setMax(1000);
        }
    }


    private void setViewListeners() {
        // TODO Auto-generated method stub
        mSeekListener = new OnSeekBarChangeListener() {
            public void onStartTrackingTouch(SeekBar bar) {

                show(mDefaultTimeout);
                mHandler.removeMessages(SHOW_PLAY_PROGRESS);
                mHandler.removeMessages(FADE_OUT_CONTROLLER);
            }

            public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
                mProgress = progress;
                if (!fromuser || mPlayer == null) {
                    return;
                }

                newPosition = (mDuration * progress) / 1000;
                newPercent = mPlayer.getBufferPercentage();
                newTime = StringUtil.generateTime(newPosition);
            }

            public void onStopTrackingTouch(SeekBar bar) {

                if (mPlayer == null) {
                    return;
                }
                nowPosition = mPlayer.getCurrentPosition();
                mPlayer.seekTo(newPosition);
                if (mOnVideoPlayListener != null) {
                    mIsVideoPlay = false;
                    mPlayer.pause();
                    mOnVideoPlayListener.onVideoLoading();
                }
            }
        };
    }

    @Override
    public void setFileName(String name) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean isShowing() {
        // TODO Auto-generated method stub
        return mShowing;
    }

    @Override
    public void show() {
        show(mDefaultTimeout);
    }

    /**
     * 显示控制器，并判断是否发送消息更新进度条
     *
     * @param timeout
     */
    public void show(int timeout) {
        if (!mShowing && mAnchor != null) {

            mShowing = true;
            ViewParent rootParent = mRoot.getParent();
            if (rootParent != null && rootParent instanceof ViewGroup) {
                LogUtil.i("zl", "MediaController show rootParent is not null...");
                ViewGroup rootParentView = (ViewGroup) rootParent;
                rootParentView.removeView(mRoot);
                return;
            }

            ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            mAnchor.addView(mRoot, tlp);

            if (mShownListener != null) {
                mShownListener.onShown();
            }
        }
        mHandler.sendEmptyMessage(SHOW_PLAY_PROGRESS);
        mHandler.removeMessages(FADE_OUT_CONTROLLER);
        mHandler.sendEmptyMessageDelayed(FADE_OUT_CONTROLLER, timeout);

        if (mProgress == 1000 && mOnVideoPlayListener != null) {
            mOnVideoPlayListener.onVideoPlayComplete();
        }

    }


    /**
     * 隐藏控制器
     */
    public void hide() {
        if (mAnchor == null) {
            return;
        }
        if (mShowing) {

            mHandler.removeMessages(SHOW_PLAY_PROGRESS);
            if (mHiddenListener != null) {
                mHiddenListener.onHidden();
            }

            if (mAnchor != null) {
                mAnchor.removeView(mRoot);
                mShowing = false;
                return;
            }
        }
    }


    public interface OnShownListener {
        public void onShown();
    }

    public interface OnHiddenListener {
        public void onHidden();
    }

    public void setOnShownListener(OnShownListener l) {
        mShownListener = l;
    }


    public void setOnHiddenListener(OnHiddenListener l) {
        mHiddenListener = l;
    }


    /**
     * getDuration拿到的播放时长不准确，重新设置，可以从服务器获取
     * 暂有问题，还需修改
     *
     * @param duration
     */
    public void setDuration(int duration) {
        this.mDuration = duration;
    }

    /**
     * 更新播放进度
     */
    private void updatePlayProgress() {
        if (mPlayer == null) {
            return;
        }
        long duration = mPlayer.getDuration();
        long position = mPlayer.getCurrentPosition();

        mDuration = duration;
        if (mScheduleProgress != null) {
            if (mDuration > 0) {
                int pos = (int) (1000L * position / mDuration);
//                LogUtil.i("zl","updatePlayProgress() pos = " + pos);
                mScheduleProgress.setProgress(pos);
            }
        }
        if (mShowing) {
            mHandler.sendEmptyMessageDelayed(SHOW_PLAY_PROGRESS, 1000 - (position % 1000));
        }
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
        if (event.getRepeatCount() == 0
                && (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
                || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keyCode == KeyEvent.KEYCODE_SPACE)) {
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) {
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK
                || keyCode == KeyEvent.KEYCODE_MENU) {
            hide();
            return true;
        } else {
            show(mDefaultTimeout);
        }
        return super.dispatchKeyEvent(event);
    }


    public View getControllerView() {
        if (mRoot == null) {
            mRoot = makeControllerView();
        }
        return mRoot;
    }

    public void hideProgressBar() {
        if (mScheduleProgress != null)
            mScheduleProgress.setVisibility(View.INVISIBLE);
    }

    public void showProgressBar() {
        if (mScheduleProgress != null)
            mScheduleProgress.setVisibility(View.VISIBLE);
    }

    class MySlideListener implements IMediaPlayer.OnSlideListener {

        @Override
        public void onSlideStart(int direction) {
            // TODO Auto-generated method stub
            if (!mIsVideoPlay || mPlayer == null) {
                return;
            }
            switch (direction) {
                case IMediaPlayer.SLIDE_STATE_LEFT:
                case IMediaPlayer.SLIDE_STATE_RIGHT:

                    break;
                case IMediaPlayer.SLIDE_STATE_UP:
                case IMediaPlayer.SLIDE_STATE_DOWN:

                    break;
                case IMediaPlayer.SLIDE_STATE_NONE:
                    break;
                default:
                    break;
            }

        }

        @Override
        public void onSlideEnd(int direction, int distance) {
            // TODO Auto-generated method stub
            if (!mIsVideoPlay || mPlayer == null) {
                return;
            }
            switch (direction) {
                case IMediaPlayer.SLIDE_STATE_LEFT:
                case IMediaPlayer.SLIDE_STATE_RIGHT:
                    break;
                case IMediaPlayer.SLIDE_STATE_UP:
                case IMediaPlayer.SLIDE_STATE_DOWN:
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onSliding(int direction, int distance) {
            // TODO Auto-generated method stub
            if (!mIsVideoPlay || mPlayer == null) {
                return;
            }
            switch (direction) {
                case IMediaPlayer.SLIDE_STATE_RIGHT://distance 大于0

                    break;
                case IMediaPlayer.SLIDE_STATE_LEFT://distance 小于0

                    break;
                case IMediaPlayer.SLIDE_STATE_UP://distance 小于0
                    break;
                case IMediaPlayer.SLIDE_STATE_DOWN://distance 大于0
                    break;
                case IMediaPlayer.SLIDE_STATE_NONE:
                    LogUtil.i(TAG, "SLIDE_STATE_NONE distance = " + distance);
                    break;

                default:
                    break;
            }
        }

    }

}
